<?php
declare (strict_types = 1);

namespace app\service;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;
use think\facade\Config;

class QiniuService
{
    protected $auth;
    protected $uploadManager;
    protected $bucketManager;
    protected $config;

    public function __construct()
    {
        $this->config = Config::get('qiniu');
        $this->auth = new Auth($this->config['access_key'], $this->config['secret_key']);
        $this->uploadManager = new UploadManager();
        $this->bucketManager = new BucketManager($this->auth);
    }

    /**
     * 获取上传凭证
     */
    public function getUploadToken()
    {
        $policy = [
            'expires' => 7200, // 2小时过期
            'returnBody' => json_encode([
                'code' => 0,
                'msg' => '上传成功',
                'data' => [
                    'url' => '$(key)',
                    'name' => '$(fname)',
                    'size' => '$(fsize)',
                    'mimeType' => '$(mimeType)',
                    'width' => '$(imageInfo.width)',
                    'height' => '$(imageInfo.height)'
                ]
            ])
        ];

        return $this->auth->uploadToken($this->config['bucket'], null, 7200, $policy);
    }

    /**
     * 上传文件
     */
    public function upload($file, $key = null)
    {
        if (empty($key)) {
            $key = date('Ymd') . '/' . uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
        }

        $token = $this->auth->uploadToken($this->config['bucket']);
        list($ret, $err) = $this->uploadManager->putFile($token, $key, $file['tmp_name']);

        if ($err !== null) {
            return ['code' => 1, 'msg' => $err->message()];
        }

        return [
            'code' => 0,
            'msg' => '上传成功',
            'data' => [
                'url' => $this->config['domain'] . '/' . $ret['key'],
                'key' => $ret['key'],
                'hash' => $ret['hash']
            ]
        ];
    }

    /**
     * 删除文件
     */
    public function delete($key)
    {
        $err = $this->bucketManager->delete($this->config['bucket'], $key);
        if ($err !== null) {
            return ['code' => 1, 'msg' => $err->message()];
        }
        return ['code' => 0, 'msg' => '删除成功'];
    }

    /**
     * 获取文件信息
     */
    public function getFileInfo($key)
    {
        $err = $this->bucketManager->stat($this->config['bucket'], $key);
        if ($err !== null) {
            return ['code' => 1, 'msg' => $err->message()];
        }
        return ['code' => 0, 'msg' => '获取成功', 'data' => $err];
    }

    /**
     * 获取文件列表
     */
    public function getFileList($prefix = '', $marker = '', $limit = 1000)
    {
        $options = [
            'limit' => $limit,
            'prefix' => $prefix,
            'marker' => $marker
        ];

        list($items, $marker, $err) = $this->bucketManager->listFiles($this->config['bucket'], $options);
        if ($err !== null) {
            return ['code' => 1, 'msg' => $err->message()];
        }

        return [
            'code' => 0,
            'msg' => '获取成功',
            'data' => [
                'items' => $items,
                'marker' => $marker
            ]
        ];
    }

    /**
     * 获取文件访问URL
     */
    public function getFileUrl($key)
    {
        return $this->config['domain'] . '/' . $key;
    }

    /**
     * 获取文件下载URL
     */
    public function getDownloadUrl($key)
    {
        return $this->auth->privateDownloadUrl($this->getFileUrl($key));
    }
} 